package service

import (
	"errors"
	"fmt"
	"time"

	// "GinAdmin/internal/model"
	// "GinAdmin/pkg/jwt"
	// "GinAdmin/pkg/database"
	"GinAdmin/core/database"
	"GinAdmin/core/jwt"
	"GinAdmin/model"

	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

// UserService 用户服务
type UserService struct {
	db *gorm.DB
}

// NewUserService 创建用户服务
func NewUserService() *UserService {
	return &UserService{
		db: database.DB,
	}
}

// Login 用户登录
func (s *UserService) Login(username, password string) (string, *model.User, error) {
	var user model.User
	if err := s.db.Where("username = ?", username).First(&user).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return "", nil, errors.New("用户不存在")
		}
		return "", nil, err
	}

	// 验证密码
	if !user.CheckPassword(password) {
		return "", nil, errors.New("密码错误")
	}

	// 更新登录信息
	now := time.Now()
	s.db.Model(&user).Updates(map[string]interface{}{
		"last_login": now,
		"updated_at": now,
	})

	// 生成JWT令牌
	token, err := s.generateToken(user.ID)
	if err != nil {
		return "", nil, err
	}

	// 不返回密码
	user.Password = ""

	// 预加载角色和部门
	if err := s.db.Preload("Roles").Preload("Depts").First(&user, user.ID).Error; err != nil {
		return "", nil, err
	}

	return token, &user, nil
}

// generateToken 生成JWT令牌
func (s *UserService) generateToken(userID uint) (string, error) {
	// 获取用户信息
	user, err := s.GetUserByID(userID)
	if err != nil {
		return "", err
	}

	// 使用jwt包生成token
	return jwt.GenerateToken(userID, user.Username)
}

// GetUserByID 通过ID获取用户
func (s *UserService) GetUserByID(id uint) (*model.User, error) {
	var user model.User
	if err := s.db.Preload("Roles").Preload("Depts").First(&user, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("用户不存在")
		}
		return nil, err
	}

	// 不返回密码
	user.Password = ""

	return &user, nil
}

// GetUserList 获取用户列表
func (s *UserService) GetUserList(page, size int, params *model.UserSearchParams) ([]model.User, int64, error) {
	var users []model.User
	var total int64

	// 构建查询
	query := s.db.Model(&model.User{})

	if params.Username != "" {
		query = query.Where("username LIKE ?", "%"+params.Username+"%")
	}

	if params.RealName != "" {
		query = query.Where("real_name LIKE ?", "%"+params.RealName+"%")
	}

	if params.Mobile != "" {
		query = query.Where("mobile LIKE ?", "%"+params.Mobile+"%")
	}

	if params.Status != 0 {
		query = query.Where("status = ?", params.Status)
	}

	if params.RoleID != 0 {
		query = query.Joins("JOIN go_user_role ON go_user_role.user_id = go_user.id").
			Where("go_user_role.role_id = ?", params.RoleID)
	}

	if params.DeptID != 0 {
		query = query.Joins("JOIN go_user_dept ON go_user_dept.user_id = go_user.id").
			Where("go_user_dept.dept_id = ?", params.DeptID)
	}

	// 计算总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * size
	if err := query.Offset(offset).Limit(size).
		Preload("Roles").Preload("Depts").
		Find(&users).Error; err != nil {
		return nil, 0, err
	}

	// 清除敏感信息
	for i := range users {
		users[i].Password = ""
	}

	return users, total, nil
}

// CreateUser 创建用户
func (s *UserService) CreateUser(req *model.CreateUserRequest) error {
	// 检查用户名是否已存在
	var count int64
	if err := s.db.Model(&model.User{}).Where("username = ?", req.Username).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("用户名已存在")
	}

	// 加密密码
	hashedPassword, err := model.EncryptPassword(req.Password)
	if err != nil {
		return err
	}

	// 创建用户
	user := model.User{
		Username: req.Username,
		Password: hashedPassword,
		RealName: req.RealName,
		Mobile:   req.Mobile,
		Email:    req.Email,
		Status:   req.Status,
		Avatar:   req.Avatar,
	}

	// 开始事务
	tx := s.db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err := tx.Create(&user).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 关联角色
	if len(req.RoleIDs) > 0 {
		var roles []model.Role
		if err := tx.Where("id IN ?", req.RoleIDs).Find(&roles).Error; err != nil {
			tx.Rollback()
			return err
		}
		if err := tx.Model(&user).Association("Roles").Replace(roles); err != nil {
			tx.Rollback()
			return err
		}
	}

	// 关联部门
	if len(req.DeptIDs) > 0 {
		var depts []model.Department
		if err := tx.Where("id IN ?", req.DeptIDs).Find(&depts).Error; err != nil {
			tx.Rollback()
			return err
		}
		if err := tx.Model(&user).Association("Depts").Replace(depts); err != nil {
			tx.Rollback()
			return err
		}
	}

	return tx.Commit().Error
}

// UpdateUser 更新用户
func (s *UserService) UpdateUser(id uint, req *model.UpdateUserRequest) error {
	var user model.User
	if err := s.db.First(&user, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("用户不存在")
		}
		return err
	}

	// 更新用户基本信息
	updates := make(map[string]interface{})

	if req.RealName != "" {
		updates["real_name"] = req.RealName
	}

	if req.Mobile != "" {
		updates["mobile"] = req.Mobile
	}

	if req.Email != "" {
		updates["email"] = req.Email
	}

	if req.Avatar != "" {
		updates["avatar"] = req.Avatar
	}

	if req.Status != 0 {
		updates["status"] = req.Status
	}

	// 开始事务
	tx := s.db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if len(updates) > 0 {
		if err := tx.Model(&user).Updates(updates).Error; err != nil {
			tx.Rollback()
			return err
		}
	}

	// 关联角色
	if len(req.RoleIDs) > 0 {
		var roles []model.Role
		if err := tx.Where("id IN ?", req.RoleIDs).Find(&roles).Error; err != nil {
			tx.Rollback()
			return err
		}
		if err := tx.Model(&user).Association("Roles").Replace(roles); err != nil {
			tx.Rollback()
			return err
		}
	}

	// 关联部门
	if len(req.DeptIDs) > 0 {
		var depts []model.Department
		if err := tx.Where("id IN ?", req.DeptIDs).Find(&depts).Error; err != nil {
			tx.Rollback()
			return err
		}
		if err := tx.Model(&user).Association("Depts").Replace(depts); err != nil {
			tx.Rollback()
			return err
		}
	}

	return tx.Commit().Error
}

// DeleteUser 删除用户
func (s *UserService) DeleteUser(id uint) error {
	// 删除用户
	if err := s.db.Delete(&model.User{}, id).Error; err != nil {
		return err
	}
	return nil
}

// ChangePassword 修改密码
func (s *UserService) ChangePassword(id uint, oldPassword, newPassword string) error {
	var user model.User
	if err := s.db.First(&user, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("用户不存在")
		}
		return err
	}

	// 验证旧密码
	if !user.CheckPassword(oldPassword) {
		return errors.New("旧密码错误")
	}

	// 加密新密码
	hashedPassword, err := model.EncryptPassword(newPassword)
	if err != nil {
		return err
	}

	// 更新密码
	if err := s.db.Model(&user).Update("password", hashedPassword).Error; err != nil {
		return err
	}

	return nil
}

// Register 用户注册
func (s *UserService) Register(req *model.RegisterRequest) (*model.User, error) {
	// 检查用户名是否已存在
	var count int64
	if err := s.db.Model(&model.User{}).Where("username = ?", req.Username).Count(&count).Error; err != nil {
		return nil, err
	}
	if count > 0 {
		return nil, fmt.Errorf("用户名已存在")
	}

	// 检查邮箱是否已存在
	if err := s.db.Model(&model.User{}).Where("email = ?", req.Email).Count(&count).Error; err != nil {
		return nil, err
	}
	if count > 0 {
		return nil, fmt.Errorf("邮箱已存在")
	}

	// 检查手机号是否已存在
	if err := s.db.Model(&model.User{}).Where("mobile = ?", req.Mobile).Count(&count).Error; err != nil {
		return nil, err
	}
	if count > 0 {
		return nil, fmt.Errorf("手机号已存在")
	}

	// 开始事务
	tx := s.db.Begin()
	if tx.Error != nil {
		return nil, tx.Error
	}
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 哈希密码
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	if err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("密码加密失败: %w", err)
	}

	// 创建用户
	user := &model.User{
		Username: req.Username,
		Password: string(hashedPassword),
		RealName: req.RealName,
		Mobile:   req.Mobile,
		Email:    req.Email,
		DeptID:   req.DeptID,
		Status:   req.Status,
		Avatar:   "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif", // 默认头像
		Remark:   req.Remark,
	}

	if err := tx.Create(user).Error; err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("创建用户失败: %w", err)
	}

	// 添加角色
	if len(req.RoleIDs) > 0 {
		var roles []model.Role
		if err := tx.Where("id IN ?", req.RoleIDs).Find(&roles).Error; err != nil {
			tx.Rollback()
			return nil, fmt.Errorf("查询角色失败: %w", err)
		}

		if err := tx.Model(user).Association("Roles").Append(roles); err != nil {
			tx.Rollback()
			return nil, fmt.Errorf("关联角色失败: %w", err)
		}
	}

	// 关联部门
	if len(req.DeptIDs) > 0 {
		var depts []model.Department
		if err := tx.Where("id IN ?", req.DeptIDs).Find(&depts).Error; err != nil {
			tx.Rollback()
			return nil, fmt.Errorf("查询部门失败: %w", err)
		}

		if err := tx.Model(user).Association("Depts").Append(depts); err != nil {
			tx.Rollback()
			return nil, fmt.Errorf("关联部门失败: %w", err)
		}
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return nil, fmt.Errorf("提交事务失败: %w", err)
	}

	// 清除密码
	user.Password = ""
	return user, nil
}
